<template>
    <rx-layout>
        <div slot="left" width="220" showButton="true">
            <rx-fit>
                <rx-category-treeeditor
                    cat-key="FORM"
                    :statisticConfig="statisticConfig"
                    :edit="true"
                    @handSelect="handSelect"
                    :async="true"
                    v-if="isShowManageTree"
                    :isAdmin="isManageToTree"
                    :checkToDel="true"
                ></rx-category-treeeditor>
            </rx-fit>
        </div>
        <div slot="center" style>
            <rx-fit :isheader="isheader">
                <div slot="toolheader" border="false" foldbtn="false">
                    <div class="table-operator">
                        <a-button type="primary" icon="plus" v-if="findAuthRight('add')" @click="add">
                            {{$ti18('rxList.newBtn',"新建")}}
                        </a-button>
                        <a-button type="primary" v-if="!isAppDevelop && selectedRowKeys.length > 0 " icon="redo"
                                  @click="changeApp('FORM',selectedRows,'pkId','name','appId','categoryId',changeAppId)">
                            {{boentI18n('list.ChangeApplication','变更应用')}}
                        </a-button>
                        <a-button v-if="selectedRowKeys.length > 0"
                                  type="primary"
                                  icon="switcher" @click="openCategoryDialog">
                            {{$ti18('rxList.changeCategory','切换分类')}}
                        </a-button>
                        <a-dropdown>
                            <a-button> {{$ti18('rxList.moreBtn',"更多")}}
                                <a-icon type="down"/>
                            </a-button>
                            <a-menu slot="overlay">
                                <a-menu-item key="1" @click="doImport" v-if="findAuthRight('add')"><i
                                    class="iconfont icondaoru"></i>
                                    {{$ti18('rxList.importBtn',"导入")}}
                                </a-menu-item>
                                <a-sub-menu>
                                    <span slot="title"><i class="iconfont icondaochu"></i>
                                        {{$ti18('rxList.exportBtn',"导出")}}
                                    </span>
                                    <a-menu-item @click="openModal('1')"><i class="iconfont icondaochu"></i>
                                        {{$ti18('rxList.exportSelected',"导出选中")}}
                                    </a-menu-item>
                                    <a-menu-item @click="openModal('2')"><i class="iconfont icondaochu"></i>
                                        {{$ti18('rxList.exportResults',"导出查询结果")}}
                                    </a-menu-item>
                                </a-sub-menu>
                                <a-menu-item
                                    key="2"
                                    @click="editOne"
                                    v-if="findAuthRight('edit') && editEnable && selectedRowKeys.length > 0"
                                    alias="formRuleEdit"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="edit"/>
                                    {{$ti18('rxList.editBtn',"编辑")}}
                                </a-menu-item>
                                <a-menu-item
                                    key="3"
                                    @click="delByIds(selectedRowKeys)"
                                    v-if="findAuthRight('delete') && removeEnable && selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'danger'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="delete"/>
                                    {{$ti18('rxList.delBtn','删除')}}
                                </a-menu-item>
                                <a-menu-item
                                    key="4"
                                    @click="changeExport(exportConf)"
                                    v-if="selectedRowKeys.length > 0"
                                    alias="formRuleDelete"
                                    :butn-type="'primary'"
                                    :show-no-right="false"
                                >
                                    <a-icon type="switcher"/>
                                    {{$ti18('rxList.changeExport','切换导出')}}
                                </a-menu-item>
                            </a-menu>
                        </a-dropdown>
                    </div>
                    <span class="search-btn-box" v-if="!isheader">
            <span class="search-btn" @click.stop="searchshow"><i class="iconfont iconguolv"></i>
                {{$ti18('rxList.leachBtn','过滤')}}
            </span>
          </span>
                </div>
                <div btnalign="right" slot="searchbar" v-if="fitSearch" @search="search" @cancel="cancel"
                     @close="closeSearchbar">
                    <a-form :layout="colLayout">
                        <a-row :gutter="24">
                            <a-col :span="colSpan">
                                <a-form-item :label="boentI18n('form.name','名称')">
                                    <a-input :placeholder="boentI18n('form.name','请输入名称','input')" v-model="queryParam.Q_NAME__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan">
                                <a-form-item :label="boentI18n('form.alias','别名')">
                                    <a-input :placeholder="boentI18n('form.alias','请输入别名','input')" v-model="queryParam.Q_ALIAS__S_LK"/>
                                </a-form-item>
                            </a-col>
                            <a-col :span="colSpan" v-if="!curApp.appId">
                                <a-form-item :label="$ti18('rxForm.appId', '应用')">
                                    <rx-search-app @change="appChange" v-model="searchApps">
                                    </rx-search-app>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <rx-grid
                    ref="table"
                    :bordered="isBorder"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :columns="columns"
                    :defaultPageSize="10"
                    url="/api-form/form/core/formSolution/query"
                    :queryParam="queryParam"
                    data-field="result.data"
                    :pageSizeOptions="['10','30','40']"
                    id-field="id"
                    :loadDataOnstart="true"
                    @selectChange="onSelectChange"
                >
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                    <span slot="appId" slot-scope="{ text, record }">
                        {{allApps[text]? $i18(allApps[text].appName): $ti18('rxList.noAppName','无')}}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                        </a-tag>
                    </span>
                  <span slot="action" slot-scope="{ text, record }" class="actionIcons">
                      <span v-if="findAuthRight('edit') && editEnable" @click.stop="edit(record)">
                          {{$ti18('rxList.editBtn',"编辑")}}
                      </span>
                      <span v-if="findAuthRight('delete') && removeEnable" @click.stop="delByIds([record.id])">
                          {{$ti18('rxList.delBtn','删除')}}
                      </span>
                      <span @click.stop="showForm(record)">
                          {{i18n('list.useForm','使用表单')}}
                      </span>
                      <span @click.stop="permissionSeting(record.id,record.bodefId)">
                          {{i18n('list.permission','权限管理')}}
                      </span>
                      <span @click.stop="deployMenu(record)" :title="i18n('list.deployMenu','发布菜单')">
                          {{i18n('list.deployMenu','发布菜单')}}
                      </span>
                      <span :title="i18n('list.publish','查看发布记录')" @click.stop="searchMenus(record.id)">
                          {{i18n('list.publish','查看发布记录')}}
                      </span>
                      <span :title="i18n('list.genExternalApi','生成对外接口')" @click.stop="genExternalApi([record])">
                          {{i18n('list.genExternalApi','生成对外接口')}}
                      </span>
                      <span :title="i18n('list.qrConfig','二维码配置')" @click.stop="qrcodeConfig(record)">
                          {{i18n('list.qrConfig','二维码配置')}}
                      </span>
                      <span @click="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                      <span v-if="!curApp.appId" @click="share(record)">{{$ti18('rxList.share','共享')}}</span>
                  </span>
                </rx-grid>
                <a-modal v-model="visible" :z-index="30000" :title="i18n('list.expConfirm','导出确认')">
                    <a-checkbox-group :options="options" v-model="types"></a-checkbox-group>
                    <div>
                        <span>{{i18n('msg.formTipMsg','（注意：表单包括PC表单、移动端表单、业务模型、业务实体）')}}</span>
                    </div>
                    <template slot="footer">
                        <a-button  type="primary" @click="doExport">
                            {{$ti18('rxForm.ackBtn','确认')}}
                        </a-button>
                        <a-button  @click="openModal('')">
                            {{$ti18('rxForm.cancelBtn','取消')}}
                        </a-button>
                    </template>
                </a-modal>
            </rx-fit>
        </div>
    </rx-layout>
</template>

<script>
import FormSolutionApi from '@/api/form/core/formSolution'
import FormPermissionApi from '@/api/form/core/formPermission'
import FormSolutionEdit from './FormSolutionEdit'
import FormImport from './FormImport'

import {BaseList, RxLayout, RxGrid, RxFit, Util, Dialog} from "@lowcode/jpaas-common-lib"
import RxCategoryTreeeditor from '@/components/redxun/rx-category-treeeditor'
import DialogBox from '../../../../assets/js/DialogBox'
import SysExternalApiApi from "@/api/system/core/sysExternalApi";
import FormQrcodeConfigList from "@/views/modules/form/core/FormQrcodeConfigList";
import changeAppJs from "@/views/modules/share/changeApp";
import { mapState} from 'vuex';
import exportApp from "@/views/modules/share/exportApp";
import FormResourceShareApi from "@/api/form/core/formResourceShare";
import AppSearch from "@/views/modules/share/AppSearch";
import RxSearchApp from "@/views/modules/share/rx-search-app";
import SysAppApi from "@/api/system/core/sysApp";
import {openUrl} from "@/utils/util";
import switchExport from "@/utils/switchExport";
import ChangeCategory from "@/views/modules/share/ChangeCategory.js"

export default {
    name: 'FormSolutionList',
    mixins: [BaseList,changeAppJs,AppSearch,switchExport,ChangeCategory],
    components: {
        FormSolutionEdit,
        RxCategoryTreeeditor,
        RxFit,
        RxLayout,
        RxGrid,
        FormImport,
        exportApp,
        RxSearchApp
    },
    computed: {
        ...mapState({
            // 所属应用
            allApps: state => state.appSetting ? state.appSetting.allApps : {}
        }),
    },
    data() {
        return {
            columns: [
                {
                    title: this.$ti18('rxList.index','序号'),
                    type: 'indexColumn',
                    dataIndex: 'serial',
                    scopedSlots: {customRender: 'serial'},
                    width: 60,
                },
                {title: this.boentI18n('form.name','名称'), dataIndex: 'name', width: 180},
                {title: this.boentI18n('form.alias','别名'), dataIndex: 'alias', width: 180},
                {title: this.boentI18n('form.app','所属应用'), dataIndex: 'appId', width: 100, sortField: 'APP_ID_',scopedSlots: {customRender: 'appId'}},
                {
                    dataIndex: 'isExport',
                    slots: { title: 'exportApp' },
                    width: 100,
                    scopedSlots: {customRender: 'isExport'}
                },
                {title: this.$ti18('rxForm.createTime','创建时间'), dataIndex: 'createTime', width: 120},
                {title: this.$ti18('rxList.action','操作'), dataIndex: 'action', scopedSlots: {customRender: 'action'}, width: 120},
            ],
            component: FormSolutionEdit,
            comment: this.i18n('list.comment','表单方案'),
            curTree: {},
            QueryData: {},
            statisticConfig: {
                type:"static_form",
                table:"FORM_SOLUTION t",
                field:"CATEGORY_ID_",
                whereConf:[]
            },
            visible:false,
            isSelected:"",
            options:[{label:this.i18n('list.form','表单'),value:"form"},{label:this.i18n('list.formulas','表间公式'),value:"formula"},{label:this.i18n('list.schemeAuth','方案权限'),value:"permission"}],
            types:["form","formula","permission"], //默认全部
            /**
             * 导出配置
             */
            exportConf:{
                Api:FormSolutionApi,
                id:"id"
            },
            //变更分类配置
            categoryConfig:{
                Api:FormSolutionApi,
                catKey:"FORM",
                gridRef:"table"
            }
        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
        this.needFilterAppId("isAppMenu");
        this.columns=this.removeAppColumn(this.curApp.appId,this.columns)
    },
    methods: {
        i18n(name,text,key){
            return this.$ti18(name,text,"formSolution",key);
        },
        boentI18n(name,text,key){
            return this.$ti18(name,text,"formBoEntity",key);
        },
        exportI18n(name,text,key){
            return this.$ti18(name,text,"appExport",key);
        },
        //资源共享
        share(record){
            let self=this;
            FormResourceShareApi.getShareApps(record.id).then(res => {
                let initData=res.data;
                if(!initData){
                    initData=[];
                }
                self.showAppDialog(initData,record.id,record.alias,record.name);
            });
        },
        showAppDialog(initData,resId,resKey,resName){
            Dialog.openSystemAppDialog({
                curVm: this, widthHeight: ['1150px', '735px'],
                data:{initSelected: initData,isDevelopApp:true,isSelectApp:true}
            }, function (self, data) {
                //保存共享信息
                FormResourceShareApi.saveShareApps(data.apps,resId,resKey,resName,"4").then(res => {
                    if (res.success && res.code == 200) {
                    }
                });
            })
        },
        doExport() {
            var exportList = [];
            //选中的导出
            if (this.isSelected == "1") {
                exportList = this.$refs.table.getSelectedRows();
                if (!exportList || exportList.length == 0) {
                    this.visible=false;
                    this.$warning({
                        title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                        content: this.i18n('msg.expMsg','请选择需要导出的记录！'),
                    });
                    return;
                }
                let solutionIds = []
                exportList.forEach((item) => {
                    solutionIds.push(item.id)
                })
                this.QueryData.params = {
                    ids: solutionIds.toString()
                }
            } else {
                // 导出所查询的
                this.QueryData.params = {
                  isQuery: 0,
                }
                this.QueryData.params = Object.assign(this.QueryData.params, this.queryParam)
            }
            if (this.$refs.table.dataAction == "") {
                this.$warning({
                    title: this.$ti18('rxMsa.masWarn.delInfo','警告'),
                    content: this.i18n('msg.nodataMsg','该分类没有数据！'),
                });
                return;
            }
            this.QueryData.params.types=this.types?JSON.stringify(this.types):"";
            FormSolutionApi.listExport(this.QueryData);
            this.visible=false;
        },

        doImport() {
            if (!this.curTree || !this.curTree.treeId || this.curTree.treeId == '0') {
                let msg= this.i18n('msg.selCategory','请选择分类！');
                this.$message.warn(msg);
                return;
            }
            var treeId = this.curTree.treeId;
            let self_=this;
            Util.open(
                {
                    component: FormImport,
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    title: this.i18n('list.formImport','表单方案导入'),
                    data: {
                        treeId: treeId,
                        callback: function (params) {
                            FormSolutionApi.doImport(params).then(res => {
                                this.isSpinning = false;
                                if (!res.success) {
                                    self_.$message.error(res.message);
                                    return;
                                }
                                self_.getUpdataSqls(res.data);
                            });
                        }
                    }
                }, function (action) {

                });
        },
        delById(ids) {
            return FormSolutionApi.del({ids: ids.join(',')})
        },
        handSelect(curRow) {
            this.curTree = curRow
            var treeId = curRow.treeId
            if (treeId != "0") {
                this.queryParam.Q_CATEGORY_ID__S_EQ = treeId;
            } else {
                delete this.queryParam.Q_CATEGORY_ID__S_EQ;
            }
            this.loadData(this.queryParam);
        },
        showForm(record) {
            let appId=record.appId;

            let key=record.tree==1?'customformtree':'customform';
            let ctxPath= process.env.VUE_APP_CONTEXT_MAIN;
            let url=`${ctxPath}/${key}/${record.alias}?appId=${appId}`;

            let title=record.name;
            openUrl({url:url,title:title,curVm:this,max:true});

        },
        permissionSeting(solutionId,boDefId) {
            FormPermissionApi.permissionSeting(this, solutionId, 'formSol',boDefId)
        },
        publish() {
            FormSolutionApi.publish().then((res) => {
                console.info(res)
            })
        },
        deployMenu(record) {
            let component = record.tree == 1 ? 'modules/form/FormSolutionShow/FormSolutionTreeShow' : 'modules/form/FormSolutionShow/FormSolutionShow'
            DialogBox.openDeploymenuDialog({
                    releaseId: record.id,
                    name: record.name,
                    key: record.alias + 'Form',
                    component: component,
                    settingType: "custom",
                    params: {formAlias: record.alias},
                    curAppObj:this.curApp,
                },
                {
                    curVm: this,
                    widthHeight: ['600px', '600px'],
                }
            )
        },
        searchMenus(releaseId) {
            var config = {
                curVm: this,
                data: {
                    releaseId: releaseId,
                },
            }
            DialogBox.openMenuReleaseDialog(config)
        },
        search() {
            this.$refs.table.loadData();
        },
        cancel() {
            this.resetSearch();
        },
        closeSearchbar() {
            //关闭过滤弹窗；（点击X触发）
            this.fitSearch = false;
        },
        genExternalApi(selectedRows) {
            if(!selectedRows || selectedRows.length==0){
                this.$message.warning(this.i18n('msg.leastOne','请至少选择一条数据!'));
                return;
            }
            this.selectCategory("EXTERNAL_API", function (categoryId){
                var ary=[];
                for (let i = 0; i < selectedRows.length; i++) {
                    ary.push( selectedRows[i].alias);
                }
                SysExternalApiApi.genExternalApi({alias: ary.join(","),type:"form",categoryId:categoryId});
            });
        },
        qrcodeConfig(record) {
            //允许不登录
            var allowNotLogin=true;
            //绑定了流程不允许不登录
            if(record.flowDefMapping && JSON.parse(record.flowDefMapping).length>0){
                allowNotLogin=false;
            }
            Util.open({
                component: FormQrcodeConfigList,
                curVm: this,
                widthHeight: ['900px', '600px'],
                title: this.i18n('list.qrConfig','二维码配置'),
                data: {
                    alias: record.alias,
                    allowNotLogin:allowNotLogin
                },
            }, function (action) {
            })
        },
        changeAppId(selectedRows){
            FormSolutionApi.saveList(selectedRows);
        },
        openModal(isSelected){
            this.visible=!this.visible;
            this.isSelected=isSelected;
            this.types=["form","formula","permission"];
            return;
        }
    },
}
</script>
<style scoped>

</style>

